package com.test.cn.message

import akka.actor.{Actor, ActorRef, ActorSystem, Props}

import scala.util.Random

class AActor extends Actor {

  var score = 100
  //接收消息并处理
  override def receive: Receive = {
    case "杀杀" => {
      val value = Random.nextInt(50)
      println(s"AActor 一拳头造成伤害${value} ")
      score -= value
      println(s"BActor 还剩下 (${score}) 血")
      if (score <= 0){
        sender() ! "你死了"
      }else{
        Thread.sleep(1000)
        sender() ! "杀杀"
      }
    }
    case "你死了" => {
      println("AActor:来生再战！！！")
      //关闭自己
      context.stop(self)
      //关闭ActorSystem
      context.system.terminate()
    }

  }
}

class BActor(actor: ActorRef) extends Actor {

  var score = 100
  //接收消息并处理
  override def receive: Receive = {
    case "开干!" => println("开干!");self ! "杀杀"
    case "你死了" => {
      println("BActor:来生再战！！！")
      //关闭自己
      context.stop(self)
      //关闭ActorSystem
      context.system.terminate()
    }
    case "杀杀" => {
      val value = Random.nextInt(50)
      println(s"BActor 一拳头造成伤害${value} ")
      score -= value
      println(s"AActor 还剩下 (${score}) 血")
      if (score <= 0){
        actor ! "你死了"
      }else{
        Thread.sleep(1000)
        actor ! "杀杀"
      }
    }
  }
}

object AActor {

  private val MyFactory = ActorSystem("myFactory")

  // 通过MyFactory.actorOf方法来创建一个actor；
  // 第一个参数传递自定义的HelloActor类，第二个参数是给actor起个名字
  private val aActor: ActorRef = MyFactory.actorOf(Props[AActor], "AActor")
  private val bActor = MyFactory.actorOf(Props(new BActor(aActor)), "BActor")

  def main(args: Array[String]): Unit = {

    bActor ! "开干!"

  }


}

